<template>
  <view class="specialty-container">
    <!-- 顶部标题栏 -->
    <view class="header animate-fade-in">
      <view class="header-main">
        <view>
          <text class="title">特产推荐</text>
          <text class="subtitle">地道特产，品味本土文化</text>
        </view>
        <view class="layout-switch" @tap="toggleLayout">
          <uni-icons :type="isGridLayout ? 'apps' : 'list'" size="24" color="#666"></uni-icons>
          <text>{{ isGridLayout ? '列表' : '网格' }}</text>
          <uni-icons :type="isGridLayout ? 'bars' : 'apps'" size="24" color="#666"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 分类筛选栏 -->
    <view class="category-wrapper">
      <scroll-view 
        scroll-x 
        class="category-scroll" 
        :show-scrollbar="false"
        @scroll="onCategoryScroll"
        :scroll-with-animation="true"
        :scroll-left="scrollLeft">
        <view class="category-list">
          <view 
            id="category-all"
            class="category-item" 
            :class="{ active: currentCategory === null }"
            @tap="switchCategory(null)">
            <uni-icons type="list" size="18" :color="currentCategory === null ? '#333' : '#666'"></uni-icons>
            <text>全部</text>
          </view>
          <view 
            v-for="category in categories" 
            :key="category.id"
            :id="'category-' + category.id"
            class="category-item"
            :class="{ active: currentCategory === category.id }"
            @tap="switchCategory(category.id)">
            <uni-icons 
              :type="currentCategory === category.id ? category.filledIcon : category.icon" 
              size="18" 
              :color="currentCategory === category.id ? '#333' : '#666'"
            ></uni-icons>
            <text>{{ category.name }}</text>
          </view>
        </view>
      </scroll-view>
      
      <!-- 添加滚动提示箭头 -->
      <view 
        v-if="showScrollHint"
        class="scroll-hint"
        :class="scrollDirection"
        @tap="scrollToNext">
        <uni-icons 
          :type="scrollDirection" 
          size="20" 
          color="rgba(102, 102, 102, 0.8)">
        </uni-icons>
      </view>
    </view>

    <!-- 特产列表 -->
    <scroll-view 
      scroll-y 
      class="specialty-list"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore">
      
      <!-- 加载中状态 -->
      <view v-if="loading && !refreshing" class="loading-wrapper">
        <text>加载中...</text>
      </view>

      <!-- 列表内容 -->
      <view v-else :class="['specialty-grid', isGridLayout ? 'grid-layout' : 'list-layout']">
        <view 
          v-for="(item, index) in specialtyList" 
          :key="item.id"
          class="specialty-item"
          :style="{ '--index': index }"
          @tap="goToDetail(item.id)">
          <!-- 图片容器 -->
          <view class="specialty-image-wrapper">
            <image 
              :src="item.imageUrl" 
              mode="aspectFill" 
              class="specialty-image" />
            <view class="specialty-sales">月售 {{ item.sales }}</view>
          </view>
          
          <!-- 信息区域 -->
          <view class="specialty-info">
            <text class="specialty-name">{{ item.name }}</text>
            <view class="specialty-rating">
              <view class="star-rating">
                <text 
                  v-for="i in 5" 
                  :key="i"
                  class="star-item"
                  :class="{ 
                    'star-filled': i <= Math.floor(item.rating),
                    'star-half': i === Math.ceil(item.rating) && item.rating % 1 !== 0
                  }">
                  ★
                </text>
              </view>
              <text class="rating-text">{{ item.rating }}分</text>
            </view>
            <view class="specialty-bottom">
              <text class="specialty-price">¥{{ item.price }}</text>
              <text class="specialty-origin">{{ item.origin }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多状态 -->
      <view v-if="specialtyList.length > 0" class="load-more">
        {{ hasMore ? '加载更多...' : '没有更多了' }}
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue';
import config from '@/config';

export default {
  name: 'Specialty',
  setup() {
    const specialtyList = ref([]);
    const loading = ref(false);
    const refreshing = ref(false);
    const currentPage = ref(1);
    const currentCategory = ref(null);
    const hasMore = ref(true);
    const isGridLayout = ref(true);
    const scrollLeft = ref(0);
    const showScrollHint = ref(false);
    const scrollDirection = ref('right');
    const currentScrollLeft = ref(0);
    const currentItemId = ref('category-all');
    const containerWidth = ref(0);
    const scrollWidth = ref(0);
    const isScrollEnd = ref(false);

    // 添加分类数据
    const categories = [
      { id: 1, name: '茶叶', icon: 'shop', filledIcon: 'shop-filled' },
      { id: 2, name: '干货', icon: 'cart', filledIcon: 'cart-filled' },
      { id: 3, name: '腊味', icon: 'cup', filledIcon: 'cup-filled' },
      { id: 4, name: '点心', icon: 'home', filledIcon: 'home-filled' },
      { id: 5, name: '水果', icon: 'gift', filledIcon: 'gift-filled' }
    ];

    // 获取特产列表
    const getSpecialtyList = async (page = 1, replace = true) => {
      if (loading.value) return;
      loading.value = true;
      
      try {
        const params = {
          page,
          pageSize: 10
        };
        
        if (currentCategory.value !== null) {
          params.categoryId = currentCategory.value;
        }

        console.log('请求参数:', params);

        const res = await uni.request({
          url: '/api/specialty/list',
          method: 'GET',
          data: params
        });

        console.log('接口返回:', res);

        if (res.statusCode === 200) {
          // 处理图片URL，添加baseURL
          const newList = res.data.data.map(item => ({
            ...item,
            imageUrl: item.imageUrl.startsWith('http') 
              ? item.imageUrl 
              : `${config.baseURL}${item.imageUrl}`
          }));
          
          console.log('获取到的数据:', newList);
          
          if (replace) {
            specialtyList.value = newList || [];
          } else {
            specialtyList.value = [...specialtyList.value, ...(newList || [])];
          }
          
          hasMore.value = newList && newList.length === 10;
          currentPage.value = page;
        } else {
          console.error('请求失败:', res.data);
          uni.showToast({
            title: '获取数据失败',
            icon: 'none',
            duration: 2000
          });
          if (replace) {
            specialtyList.value = [];
          }
        }
      } catch (e) {
        console.error('获取特产列表失败:', e);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 2000
        });
        if (replace) {
          specialtyList.value = [];
        }
      } finally {
        loading.value = false;
        refreshing.value = false;
      }
    };

    // 切换分类
    const switchCategory = (categoryId) => {
      if (loading.value) return;
      
      currentCategory.value = categoryId;
      currentPage.value = 1;
      hasMore.value = true;
      
      getSpecialtyList(1, true);
    };

    // 下拉刷新
    const onRefresh = () => {
      refreshing.value = true;
      getSpecialtyList(1);
    };

    // 加载更多
    const loadMore = () => {
      if (!hasMore.value || loading.value) return;
      getSpecialtyList(currentPage.value + 1, false);
    };

    // 跳转详情页
    const goToDetail = (id) => {
      uni.navigateTo({
        url: `/pages/specialty/detail?id=${id}`
      });
    };

    // 切换布局方法
    const toggleLayout = () => {
      isGridLayout.value = !isGridLayout.value;
      console.log('当前布局:', isGridLayout.value ? '网格' : '列表');
    };

    // 检查是否需要显示滚动提示
    const checkScrollable = async () => {
      await new Promise(resolve => setTimeout(resolve, 100));
      
      const query = uni.createSelectorQuery();
      query.select('.category-list').boundingClientRect(data => {
        scrollWidth.value = data.width;
      }).exec();
      
      query.select('.category-scroll').boundingClientRect(data => {
        containerWidth.value = data.width;
        scrollDirection.value = 'right';
        showScrollHint.value = scrollWidth.value > containerWidth.value;
      }).exec();
    };

    // 处理分类滚动事件
    const onCategoryScroll = (e) => {
      const { scrollLeft: left, scrollWidth: width } = e.detail;
      const isNearEnd = left + containerWidth.value >= width - 20;
      
      scrollDirection.value = isNearEnd ? 'left' : 'right';
      isScrollEnd.value = isNearEnd;
      
      showScrollHint.value = scrollWidth.value > containerWidth.value;
    };

    // 点击箭头滚动到下一屏
    const scrollToNext = () => {
      if (isScrollEnd.value) {
        scrollLeft.value = 0;
      } else {
        scrollLeft.value += containerWidth.value * 0.8;
      }
    };

    onMounted(() => {
      getSpecialtyList();
      checkScrollable();
    });

    return {
      specialtyList,
      loading,
      refreshing,
      currentCategory,
      hasMore,
      switchCategory,
      onRefresh,
      loadMore,
      goToDetail,
      isGridLayout,
      toggleLayout,
      categories,
      scrollLeft,
      showScrollHint,
      scrollDirection,
      onCategoryScroll,
      scrollToNext,
      currentScrollLeft,
      currentItemId
    };
  }
};
</script>

<style scoped>
.specialty-container {
  padding: 20px;
  background: linear-gradient(to bottom, #f8f8f8, #fff);
  min-height: 100vh;
}

.category-wrapper {
  position: relative;
  margin: 0 -20px 20px;
  overflow: hidden;
}

.category-scroll {
  width: 100%;
  white-space: nowrap;
  background: transparent;
}

.category-list {
  display: inline-flex;
  padding: 0 20px;
  gap: 12px;
}

.category-item {
  display: inline-flex;
  align-items: center;
  padding: 10px 16px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  font-size: 14px;
  color: #666;
  gap: 4px;
  transform: scale(0.95);
  white-space: nowrap;
}

.category-item text {
  margin-left: 4px;
}

.category-item.active {
  transform: translateY(-2px) scale(1);
  background: #ffe4e1;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.15);
  color: #333;
}

.specialty-list {
  height: calc(100vh - 180px);
  padding: 0;
}

.specialty-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  padding: 0;
}

.specialty-item {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0,0,0,0.06);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(0,0,0,0.03);
  animation: scaleIn 0.5s ease-out forwards;
  opacity: 0;
}

.specialty-item:active {
  transform: scale(0.98);
}

.specialty-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0,0,0,0.12);
}

.specialty-image-wrapper {
  position: relative;
  padding-top: 75%;
  overflow: hidden;
}

.specialty-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.4s ease;
}

.specialty-item:hover .specialty-image {
  transform: scale(1.05);
}

.specialty-sales {
  position: absolute;
  right: 10px;
  bottom: 10px;
  padding: 4px 12px;
  border-radius: 20px;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 12px;
  backdrop-filter: blur(4px);
}

.specialty-info {
  padding: 16px;
}

.specialty-name {
  font-size: 17px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 8px;
}

.specialty-rating {
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.star-rating {
  display: inline-flex;
  align-items: center;
}

.star-item {
  font-size: 14px;
  color: #ddd;
  margin-right: 2px;
}

.star-filled {
  color: #ffd700;
}

.star-half {
  position: relative;
  background: linear-gradient(90deg, #ffd700 50%, #ddd 50%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.rating-text {
  margin-left: 8px;
  font-size: 13px;
  color: #666;
}

.specialty-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.specialty-price {
  font-size: 20px;
  background: linear-gradient(45deg, #ff6b6b, #ff8787);
  -webkit-background-clip: text;
  color: transparent;
  font-weight: bold;
}

.specialty-origin {
  font-size: 12px;
  color: #999;
  background: rgba(255, 255, 255, 0.9);
  padding: 4px 12px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.loading-wrapper {
  padding: 40px 0;
  text-align: center;
  color: #999;
  background: linear-gradient(90deg, #f0f0f0 25%, #f8f8f8 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 12px;
}

.load-more {
  text-align: center;
  padding: 20px 0;
  color: #999;
  font-size: 13px;
}

.empty-state {
  padding: 100px 0;
  text-align: center;
  color: #999;
  animation: fadeIn 0.8s ease-out;
}

.empty-image {
  width: 200px;
  height: 200px;
  margin-bottom: 20px;
  opacity: 0.7;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

/* 暗黑模式适配 */
@media (prefers-color-scheme: dark) {
  .specialty-container {
    background: linear-gradient(to bottom, #1a1a1a, #222);
  }

  .category-item {
    background: rgba(255, 255, 255, 0.1);
    color: #ccc;
  }

  .category-item.active {
    background: rgba(255, 107, 107, 0.2);
    color: #fff;
  }

  .specialty-item {
    background: rgba(255, 255, 255, 0.05);
    border-color: rgba(255, 255, 255, 0.1);
  }

  .specialty-name {
    color: #fff;
  }

  .specialty-origin {
    background: rgba(255, 255, 255, 0.1);
    color: #ccc;
  }

  .loading-wrapper {
    background: linear-gradient(90deg, #222 25%, #2a2a2a 50%, #222 75%);
  }
}

/* 头部样式 */
.header {
  margin-bottom: 20px;
}

.header-main {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 25px;
}

.title {
  display: block;
  font-size: 32px;
  font-weight: bold;
  background: linear-gradient(45deg, #333, #666);
  -webkit-background-clip: text;
  color: transparent;
  margin-bottom: 6px;
}

.subtitle {
  display: block;
  font-size: 14px;
  color: #999;
  letter-spacing: 0.5px;
}

/* 布局切换按钮样式 */
.layout-switch {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  backdrop-filter: blur(10px);
  transition: all 0.3s;
}

.layout-switch:active {
  transform: scale(0.95);
  background: rgba(255, 255, 255, 0.95);
}

.layout-switch text {
  margin: 0 8px;
  font-size: 14px;
  color: #666;
}

/* 布局切换动画 */
.layout-transition-move {
  transition: all 0.5s ease;
}

.layout-transition-enter-active,
.layout-transition-leave-active {
  transition: all 0.5s ease;
}

.layout-transition-enter-from,
.layout-transition-leave-to {
  opacity: 0;
  transform: scale(0.9);
}

.layout-transition-leave-active {
  position: absolute;
}

/* 优化��有的过渡效果 */
.grid-layout,
.list-layout {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.specialty-item {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 暗黑模式适配 */
@media (prefers-color-scheme: dark) {
  .layout-switch {
    background: rgba(255, 255, 255, 0.1);
  }
  
  .layout-switch text {
    color: #ccc;
  }
}

/* 黑模式下的图标颜色适配 */
@media (prefers-color-scheme: dark) {
  .category-item.active .uni-icons {
    color: #fff !important;
  }
}

/* 网格布局样式 */
.grid-layout {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.grid-layout .specialty-item {
  display: flex;
  flex-direction: column;
}

.grid-layout .specialty-image-wrapper {
  width: 100%;
  padding-top: 90%;
}

/* 列表布局样式 */
.list-layout {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.list-layout .specialty-item {
  display: flex;
  flex-direction: row;
  height: 180px;
  padding: 0;
}

.list-layout .specialty-image-wrapper {
  width: 180px;
  height: 180px;
  padding-top: 0;
  flex-shrink: 0;
}

.list-layout .specialty-image {
  position: relative;
  border-radius: 16px 0 0 16px;
}

.list-layout .specialty-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 12px 16px;
}

.list-layout .specialty-bottom {
  margin-top: auto;
}

/* 布局切换动画 */
.specialty-grid {
  transition: all 0.3s ease;
}

.specialty-item {
  transition: all 0.3s ease;
}

/* 布局切换动画相关样式 */
.specialty-grid {
  position: relative;
  will-change: transform, opacity;
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 网格布局动画 */
.grid-layout {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.grid-layout .specialty-item {
  transform-origin: center;
  animation: gridEnter 0.5s cubic-bezier(0.4, 0, 0.2, 1) forwards;
}

/* 列表布局动画 */
.list-layout {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.list-layout .specialty-item {
  transform-origin: top center;
  animation: listEnter 0.5s cubic-bezier(0.4, 0, 0.2, 1) forwards;
}

/* 布局切换时的项目动画 */
.specialty-item {
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: transform, opacity;
}

/* 网格进入动画 */
@keyframes gridEnter {
  from {
    opacity: 0;
    transform: scale(0.8) translateY(20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

/* 进入动画 */
@keyframes listEnter {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 每项目添加延迟动画 */
.specialty-item {
  animation-fill-mode: both;
}

.grid-layout .specialty-item:nth-child(2n) {
  animation-delay: 0.1s;
}

.list-layout .specialty-item {
  animation-delay: calc(var(--index) * 0.05s);
}

/* 添加滚动提示箭头样式 */
.category-wrapper {
  position: relative;
}

.scroll-hint {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(4px);
  cursor: pointer;
  z-index: 1;
}

.scroll-hint:active {
  transform: translateY(-50%) scale(0.95);
}

.scroll-hint.right {
  animation: bounceRight 1s infinite;
  right: 10px;
  left: auto;
}

.scroll-hint.left {
  animation: bounceLeft 1s infinite;
  left: 10px;
  right: auto;
}

/* 添加箭头动画 */
@keyframes bounceRight {
  0%, 100% {
    transform: translateY(-50%);
  }
  50% {
    transform: translateY(-50%) translateX(2px);
  }
}

@keyframes bounceLeft {
  0%, 100% {
    transform: translateY(-50%);
  }
  50% {
    transform: translateY(-50%) translateX(-2px);
  }
}

/* 暗黑模式适配 */
@media (prefers-color-scheme: dark) {
  .scroll-hint {
    background: rgba(255, 255, 255, 0.15);
  }
  
  .scroll-hint:hover {
    background: rgba(255, 255, 255, 0.2);
  }
}
</style>